package com.vf.s.mvc.biz.controller;


import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.vf.core.controller.BaseController;
import com.vf.core.util.GpsCoordinateUtils;
import com.vf.s.common.model.biz.BizLayer;
import com.vf.s.common.model.biz.BizPanorama;
import com.vf.s.common.model.biz.BizPoint;
import com.vf.s.common.model.biz.BizPolygon;
import com.vf.s.common.model.biz.BizVideo;
import com.vf.s.common.primitive.PointPrimitive;
import com.vf.s.common.render.PointRender;
import com.vf.s.common.render.PropertyRender;
import com.vf.s.mvc.biz.service.BizPointService;
import com.vf.s.mvc.biz.service.BizPropertyService;

public class BizPointController extends BaseController {
	
	@Inject
	private BizPointService srv;
	
	@Inject
	private BizPropertyService propertyService;
	
	public void list() {
		render("list.html");
	}
	
	public void index() {
		this.set("sceneId", this.get("sceneId"));
		BizPoint bizPoint=BizPoint.dao.findById(get("pointId"));
		this.set("bizPoint", bizPoint);
		render("list.html");
	}
	public void operation() {
		this.set("pointId", this.get("pointId"));
		this.set("bizPoint",BizPoint.dao.findById(get("pointId")));
		render("operation.html");
	}
	
	/**
	 * 编辑点信息
	 */
	public void edit() {
		this.set("bizPoint", BizPoint.dao.findById(get("pointId")));
		render("edit.html");
	}
	
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String name = getPara("name");
		String layerId = getPara("layerId");
		
		String select = " select *  ";
		String sqlExceptSelect = " from " + BizPoint.TABLE_NAME + " o  where 1=1 ";
		if (!StrKit.isBlank(name)) {
			sqlExceptSelect += " and o.name like '%" + name + "%'  ";
		}
		
		if (!StrKit.isBlank(layerId)) {
			sqlExceptSelect += " and o.layerId = '" + layerId + "'  ";
		}
		Page<BizPoint> page = BizPoint.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	

	
	public void pointForProVideo() {
		String id = this.get("id");
		if(!StrKit.isBlank(id)) {
			this.set("bizVideo", BizVideo.dao.findById(id));
		}
		render("pointForProVideo.html");
	}
	
	public void pointForProVSrc() {
		render("pointForProVSrc.html");
	}
	
	public void pointForProImgSrc() {
		render("pointForProImgSrc.html");
	}
	
	public void pointForProPanorama() {
		String id = this.get("id");
		if(!StrKit.isBlank(id)) {
			this.set("bizPanorama", BizPanorama.dao.findById(id));
		}
		this.set("pointId", this.get("pointId"));
		render("pointForProPanorama.html");
	}
	
	public void pointForPropertyPSrc() {
		String id = this.get("id");
		if(!StrKit.isBlank(id)) {
			this.set("bizVideo", BizVideo.dao.findById(id));
		}
		this.set("pointId", this.get("pointId"));
		render("pointForPropertyPSrc.html");
	}
	
	public void delete() throws Exception {
		String id = getPara("id");
		if (BizPoint.dao.deleteById(id)) {
			renderSuccess("删除成功！");
		} else {
			renderError("删除失败！");
		}
	}

	
	public void getById() throws Exception {
		String id = getPara("id");
		BizPoint bizPoint=BizPoint.dao.findById(id);
		if (bizPoint!=null) {
			renderSuccess("成功！",bizPoint);
		} else {
			renderError("数据已经不存在！");
		}
	}
	
	/**
	 * 点操作菜单
	 */
	public void pointForMenu() {
		this.set("sceneId", this.get("sceneId"));
		BizPoint bizPoint=BizPoint.dao.findById(get("pointId"));
		this.set("bizPoint", bizPoint);
		render("pointForMenu.html");
	}
	
	
	/**
	 * 保存点
	 */
	public void save() {
		BizPoint model = getModel(BizPoint.class);
		BizPoint dbBizPoint=BizPoint.dao.findById(model.getId());
		if(dbBizPoint!=null) {
			if (model.update() ) {
				renderSuccess("更新成功！",BizPoint.dao.findById(model.getId()));
			} else {
				renderError("更新失败！");
			}
		}else {
			if(model.save()) {
				renderSuccess("保存成功！",BizPoint.dao.findById(model.getId()));
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	/**
	 * 点样式
	 */
	public void pointForStyle() {
		this.set("sceneId", this.get("sceneId"));
		BizPoint bizPoint=BizPoint.dao.findById(get("pointId"));
		this.set("bizPoint", bizPoint);
		render("pointForStyle.html");
	}
	
	public void setStyle() {
		BizPoint model = getModel(BizPoint.class);
		if(model!=null ) {
			if (model.update()) {
				PointPrimitive pointPrimitive=new PointPrimitive();
				pointPrimitive.setPoint(BizPoint.dao.findById(model.getId()));
				renderSuccess("设置成功！",pointPrimitive);
			} else {
				renderError("设置失败！");
			}
		}else {
			renderError("点已不存在！");
		}
	}
	
	
	/***
	 * 保存样式
	 */
	
	public void saveForStyle() {
		BizPoint model = getModel(BizPoint.class);
		BizPoint dbBizPoint=BizPoint.dao.findById(model.getId());
		if(dbBizPoint!=null) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		}
		
//		String pointId=this.getPara("pointId");
//		String styleId=this.getPara("styleId");
//		String event=this.getPara("event");
//		BizPoint bizPoint=BizPoint.dao.findById(pointId);
//		if(bizPoint!=null ) {
//			if(StrKit.equals(event, "DEFAULT")) {
//				bizPoint.setDefaultStyleId(styleId);
//			}
//			else  if(StrKit.equals(event, "HOVER")) {
//				bizPoint.setHoverStyleId(styleId);
//			}
//			else  if(StrKit.equals(event, "SELECTED")) {
//				bizPoint.setSelectedStyleId(styleId);
//			}else {
//				bizPoint.setDefaultStyleId(styleId);
//			}
//			if (bizPoint.update()) {
//				renderSuccess("成功！",bizPoint);
//			} else {
//				renderError("失败！");
//			}
//		}else {
//			renderError("点或样式不存在！");
//		}
	}
	
	public void pointForGrid() {
		String xmin=this.getPara("xmin");
		String ymin=this.getPara("ymin");
		String xmax=this.getPara("xmax");
		String ymax=this.getPara("ymax");
		int count=this.getParaToInt("count",10);
		String sceneId=this.getPara("sceneId");
		String sqlExceptSelect=" FROM "+BizPoint.TABLE_NAME+" P, BIZ_LAYER L   "
				+ " WHERE P.ID=L.ID and P.SCENEID=? and  L.SCENEID=?   "
				+ " AND CAST(P.x AS DECIMAL(10,7)) >= CAST( '"+xmin+"' AS DECIMAL(10,7)) and CAST(P.x AS DECIMAL(10,7))< CAST( '"+xmax+"' AS DECIMAL(10,7)) " 
				+ " AND CAST(P.y AS DECIMAL(10,7)) >= CAST( '"+ymin+"' AS DECIMAL(10,7)) and CAST(P.y AS DECIMAL(10,7))< CAST( '"+ymax+"' AS DECIMAL(10,7)) " 
				+ " order by L.sort asc ";
		//点
		Page<BizPoint> pages=BizPoint.dao.paginate(1, count, " SELECT P.*,L.show ",sqlExceptSelect,sceneId,sceneId);
		renderSuccess("成功！",pages.getList());
	}
	
	
	/**
	 * 获取点信息
	 */
	public void getPointById() {
		BizPoint bizPoint=BizPoint.dao.findById(getPara("id"));
		if(bizPoint!=null) {
			PointRender pointRender=new PointRender();
			PropertyRender property=propertyService.getObjProperty(bizPoint.getId(), this.getPara("event"),null);
			pointRender.setPoint(bizPoint);
			pointRender.setProperty(property);
			renderSuccess("成功！",pointRender);
		}else {
			renderError("信息不存在！");
		}
	}
	
	public void getPointPropertyById() {
		BizPoint bizPoint=BizPoint.dao.findById(getPara("id"));
		if(bizPoint!=null) {
			PointRender pointRender=new PointRender();
			PropertyRender property=propertyService.getObjProperty(bizPoint.getId(), this.getPara("event"),getPara("type"));
			pointRender.setPoint(bizPoint);
			pointRender.setProperty(property);
			renderSuccess("成功！",pointRender);
		}else {
			renderError("信息不存在！");
		}
	}
	
	public void pointUpteRegion() {
		String sceneId=this.getPara("sceneId","4a0f459760a74e44a437c62c711c4273");
		
		String code = this.getPara("code");
			
		List<BizPoint> bizPointList=BizPoint.dao.find("Select * from "+BizPoint.TABLE_NAME+" where sceneId=? ",sceneId);
		
		List<BizLayer> bizLayerList = BizLayer.dao.find("SELECT * FROM "+BizLayer.TABLE_NAME+" WHERE PARENTID IN (SELECT ID FROM "+BizLayer.TABLE_NAME+" WHERE code='"+code+"' and sceneId=? ) AND TYPE='polygon' ",sceneId);
		for(BizLayer bizLayer:bizLayerList) {
			BizPolygon bizPolygon=BizPolygon.dao.findById(bizLayer.getId());
			
			if(bizPolygon!=null) {
				String jsonStr=bizPolygon.getPoints();
				net.sf.json.JSONArray jsonObject = net.sf.json.JSONArray.fromObject(jsonStr);
				com.vf.core.entity.Point[] polygon=new com.vf.core.entity.Point[jsonObject.size()];
				for(int i=0;i<jsonObject.size();i++) {
					Object obj=jsonObject.get(i);
					net.sf.json.JSONObject json=net.sf.json.JSONObject.fromObject(obj);
					com.vf.core.entity.Point point=new com.vf.core.entity.Point(Double.parseDouble(json.getString("x")),Double.parseDouble(json.getString("y"))); 
					polygon[i]=point;
				}
				
				//多边形目录
				//BizLayer pBizLayer=BizLayer.dao.findById(bizLayer.getParentId());
				
				for(BizPoint bizPoint:bizPointList) {
					boolean isOK=GpsCoordinateUtils.pointInPolygon(polygon, Double.parseDouble(bizPoint.getX()), Double.parseDouble(bizPoint.getY()));
					if(isOK) {
						if(StrKit.isBlank(bizPoint.getCode())) {
							bizPoint.setCode(bizPolygon.getId()+"-");
						}else {
							if(!bizPoint.getCode().contains(bizPolygon.getId())) {
								bizPoint.setCode(bizPolygon.getId()+"-"+bizPoint.getCode());
							}
						}
						if(StrKit.isBlank(bizLayer.getCode())) {
							bizLayer.setCode(bizPolygon.getId()+"-");
						}else {
							if(!bizLayer.getCode().contains(bizPolygon.getId())) {
								bizLayer.setCode(bizPolygon.getId()+"-"+bizLayer.getCode());
							}
						}
						bizLayer.update();
						bizPoint.update();
//						BizLayer pointLayer = BizLayer.dao.findById(bizPoint.getId());//点对应图层
//						if(pointLayer!=null) {
//							//点对应目录 和 多边形是否
//							BizLayer bizLayerPoint=BizLayer.dao.findFirst("SELECT * FROM "+BizLayer.TABLE_NAME+" WHERE PARENTID=? AND code=? ",pBizLayer.getId(),pointLayer.getParentId());
//							if(bizLayerPoint ==null) {
//								bizLayerPoint=BizLayer.dao.findById(pointLayer.getParentId());
//								bizLayerPoint.setParentId(pBizLayer.getId());
//								bizLayerPoint.setCode(pointLayer.getParentId());
//								bizLayerPoint.setId(UuidUtil.getUUID());
//								bizLayerPoint.save();
//							}
//							pointLayer.setParentId(bizLayerPoint.getId());
//							pointLayer.update();
//							
//						}
					}
					
				}
			}
		}
		renderSuccess("");
	}
	
	/**
	 * 更新高度
	 */
	public void updateHeights() {
		String points=this.getPara("points");
		if(!StrKit.isBlank(points)) {
			net.sf.json.JSONArray array=net.sf.json.JSONArray.fromObject(points);
			List<String> sqlList=new LinkedList<String>();
			for(Object obj:array) {
				net.sf.json.JSONObject jsonObj=net.sf.json.JSONObject.fromObject(obj);
				if(jsonObj!=null && jsonObj.has("id") && jsonObj.has("z") && !StrKit.isBlank(jsonObj.getString("z"))) {
					sqlList.add("UPDATE BIZ_POINT SET z = '"+jsonObj.getString("z")+"' WHERE id = '"+jsonObj.getString("id")+"' ");
				}
			}
			int[] sqls=Db.batch(sqlList, sqlList.size());
			if(sqls.length>0) {
				renderSuccess("执行成功！");
			}else {
				renderError("执行失败！");
			}
		}else {
			renderError("参数必填！");
		}
	}
	
	public void updateHeight() {
		String id=this.getPara("id");
		String z=this.getPara("z");
		BizPoint bizPoint=BizPoint.dao.findById(id);
		if(bizPoint!=null) {
			bizPoint.setZ(z);
			if(bizPoint.update()) {
				renderSuccess("执行成功！");
			}else {
				renderError("执行失败！");
			}
		}else {
			renderError("参数必填！");
		}
	}
	
	ExecutorService executor = Executors.newFixedThreadPool(20);
	public void batchSaveStyle() throws Exception {
		String layerId=this.getPara("layerId");
		String styleId=this.getPara("styleId");
		String event=this.getPara("event");
		renderSuccess("异步处理中！！！");
		
		BizLayer bizLayer=BizLayer.dao.findById(layerId);
		if(bizLayer!=null) {
			if(StrKit.equals("DEFAULT", event)) {
				bizLayer.setDefaultStyleId(styleId);
			}
			else if(StrKit.equals("HOVER", event)) {
				bizLayer.setHoverStyleId(styleId);
			}
			else if(StrKit.equals("SELECTED", event)) {
				bizLayer.setSelectedStyleId(styleId);
				
			}
			bizLayer.update();
		}
		
	    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
	        @Override
	        public Integer get() {
	            try {
	        		List<BizLayer> bizLayers=BizLayer.dao.find("SELECT * FROM "+BizLayer.TABLE_NAME+" WHERE PARENTID=? AND TYPE='point' ",layerId);
	        		BizPoint bizPoint;
	        		for(BizLayer bizLayer:bizLayers) {
	        			bizPoint=BizPoint.dao.findById(bizLayer.getId());
	        			if(bizPoint!=null) {
	        				bizPoint.update();
	        			}
	        		}
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	            return 3;
	        }
	    }, executor);
	    future.thenAccept(e -> System.out.println(e));
	}
	
	
	
	
}
